//
//  QLTabBar.swift
//  WeiBo01
//
//  Created by 黄跃奇 on 16/9/21.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

//MARK: - 1.(代理)定义代理协议
protocol QLTabBarDelegate: NSObjectProtocol {
    func clickFinishedComposeButton()
}

class QLTabBar: UITabBar {
    
    //MARK: - 1.(闭包)点击撰写按钮执行的闭包
    var composeButtonClosure: (()->())?
    
    //MARK: - 2.(代理)设置代理属性
    weak var qlDelegate: QLTabBarDelegate?

    //全局按钮属性
    var composeButton: UIButton?
    
    //表示使用手写代码去创建对象
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    //设置UI界面，添加控件
    func setupUI() {
        
        //设置背景图片防止push时右边出现黑色效果
        backgroundImage = UIImage(named: "tabbar_background")
        
        composeButton = UIButton()
        
        //添加按钮的点击事件
        composeButton?.addTarget(self, action: #selector(composeButtonAction), for: .touchUpInside)
        
        //设置图片
        composeButton!.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        composeButton!.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        //设置背景图片
        composeButton!.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        composeButton!.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        //设置大小
        composeButton!.sizeToFit()
        addSubview(composeButton!)
        
        
    }
    
    //实现按钮的点击事件
    @objc private func composeButtonAction() {
        
        print("haha")
        
        //MARK: - 2.(闭包)执行闭包
        composeButtonClosure?()
        
        //MARK: - 3.(代理)使用代理对象调用代理方法
        qlDelegate?.clickFinishedComposeButton()
        
    }
    
//    布局子控件
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //设置按钮的中心点
        composeButton?.centerX = width / 2
        composeButton?.centerY = height / 2
        
        //计算每个按钮的宽度
        let btnWidth = width / 5
        //记录遍历到的按钮的索引
        var index = 0
        for value in subviews {
            //获取需要的按钮
            if value.isKind(of: NSClassFromString("UITabBarButton")!) {
                value.width = btnWidth
                
                value.x = CGFloat(index) * btnWidth
                
                index += 1
                
                if index == 2 {
                    index += 1
                }
            }
        }
    }
}




